package com.example.cardemo

import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.example.cardemo.adapter.BrandAdapter
import com.example.cardemo.bean.BrandBean
import com.example.cardemo.databinding.ActivityBrandBinding
import com.example.cardemo.utils.CarApi
import com.example.cardemo.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class BrandActivity : AppCompatActivity() {
    val binding: ActivityBrandBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_brand)
    }
    val mDatas = mutableListOf<BrandBean.ResultBean>()
    val adapter: BrandAdapter by lazy {
        BrandAdapter(this, mDatas)
    }
    var letter_msg = "当前品牌首字母:"
    var letter = "A"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.adapter = adapter
        binding.name = letter_msg + letter
        binding.brandRecyclerview.layoutManager = GridLayoutManager(this, 4)
        binding.brandRecyclerview.adapter = adapter
        loadDatas(letter)
        binding.brandButton.setOnClickListener {
            val lt = binding.brandEdittext.text.toString().trim().uppercase()
            if (!TextUtils.isEmpty(lt) && lt != letter) {
                letter = lt
                binding.name = letter_msg + letter
                loadDatas(letter)
            }
        }
    }

    private fun loadDatas(letter: String) {
        val api = RetrofitUtils.getApi(CarApi.base_url, CarApi::class.java)
        val call = api.getCarBrand(CarApi.key, letter)
        call?.enqueue(object : Callback<BrandBean> {
            override fun onResponse(call: Call<BrandBean>, response: Response<BrandBean>) {
                val bean: BrandBean? = response.body()
                mDatas.clear()
                bean?.result?.let {
                    mDatas.addAll(it)
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<BrandBean>, t: Throwable) {
                Toast.makeText(this@BrandActivity, "获取失败，原因是： ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}